package socket;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;

/**
 * 模拟 初始化连接 粗识别 细识别 精确识别 打螺丝
 */
@ClientEndpoint
public class SlamToWebSocketClientDemo {

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(SlamToWebSocketClientDemo.class, new URI(WS_URL));

            // 保持连接直到程序被终止
            latch.await(24, TimeUnit.HOURS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final String WS_URL = "ws://192.168.3.152:11004/api/speech/ds/voice";
    private static CountDownLatch latch = new CountDownLatch(1);
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("已连接 websocket：" + WS_URL);

        try {
            String initMsg = "{\"signal\":\"attachUser\",\"data\":\"{\\\"userId\\\":\\\"c-1\\\"}\",\"id\":5}";
            session.getBasicRemote().sendText(initMsg);
            System.out.println("初始化连接: " + initMsg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            JSONObject json = new JSONObject(message);
            String signal = json.optString("signal", "");

            if ("attachIssued".equals(signal)) {
                String dataStr = json.optString("data", "{}");
                JSONObject data = new JSONObject(dataStr);
                String step = data.optString("step", "");
                String description = data.optString("description", "");
                System.out.println("收到消息: " + step + ", description信息: " + description);
                System.out.println("收到消息，完整内容: " + message);
            }

            // 检查信号类型和场景
            if ("attachIssued".equals(json.getString("signal")) &&
                    "lockAttachment".equals(json.getString("scence"))) {

                String step = json.getJSONObject("data").getString("step");

                // 根据step值发送不同响应
                switch (step) {
                    case "attach-roughRecognition":
                        sendAttachResponse("roughRecognition", "attach-roughRecognition", "", "1131340426738012160");
                        break;
                    case "attach-fineRecognition":
                        sendAttachResponse("fineRecognition", "attach-fineRecognition", "c-2", "1131351041548357632");
                        break;
                    case "attach-accurateRecognition":
                        sendAttachResponse("accurateRecognition", "attach-accurateRecognition", "c-2", "1131351041548357632");
                        break;
                    case "attach-twistTheScrew":
                        sendAttachResponse("twistTheScrew", "attach-twistTheScrew", "c-1", "1131351041548357632");
                        break;
                    case "attach-end":
                        sendAttachResponse("end", "attach-end", "c-2", "1131351041548357632");
                        break;
                    default:
                        System.out.println("Unknown step type: " + step);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendAttachResponse(String mapping, String step, String toRole, String id) throws IOException {
        String description = getDescription(step);
        JSONObject dataJson = new JSONObject();
        dataJson.put("qas", "server");
        dataJson.put("mapping", mapping);
        dataJson.put("toRole", toRole);
        dataJson.put("description", description);
        dataJson.put("step", step);
        dataJson.put("id", id);
        dataJson.put("fromRole", "6");

        JSONObject messageJson = new JSONObject();
        messageJson.put("signal", "attachIssuedBack");
        messageJson.put("data", dataJson.toString());

        String message = messageJson.toString();
        session.getBasicRemote().sendText(message);
        System.out.println("发送消息: " + step);
        System.out.println("发送消息，完整内容: " + message);

    }

    private String getDescription(String step) {
        switch (step) {
            case "attach-roughRecognition":
                return "";
            case "attach-fineRecognition":
                return "细识别";
            case "attach-accurateRecognition":
                return "精确识别";
            case "attach-twistTheScrew":
                return "拧螺丝";
            case "attach-end":
                return "结束(回到初始状态)";
            default:
                return "";
        }
    }

    @OnError
    public void onError(Throwable t) {
        System.err.println("WebSocket error:");
        t.printStackTrace();
    }

    @OnClose
    public void onClose(CloseReason reason) {
        System.out.println("Connection closed: " + reason);
        latch.countDown();
    }

}